﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using PanasonicWarranty.Business;
using System.Web.UI.HtmlControls;
using Utils;
using System.IO;
using Settings;
using System.Data;
using System.Data.SqlClient;
namespace PanasonicWarranty.UI
{
    public partial class UnRegisterWarranty : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtSearchFromDate.Text = DateTime.Now.AddDays(-31).ToShortDateString();
                txtSearchToDate.Text = DateTime.Now.ToShortDateString();
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                BindGridData();
            }
        }

        private void BindGridData()
        {
            try
            {
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRow = 0;
                string model = txtSearchModel.Text.Trim();
                string productcode = txtSearchProductCode.Text.Trim();
                int? agencyid = null;
                if (!string.IsNullOrEmpty(ddlSearchAgency.SelectedValue))
                    agencyid = int.Parse(ddlSearchAgency.SelectedValue);
                DateTime? fromRegisterDate = string.IsNullOrWhiteSpace(txtSearchFromDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchFromDate.Text.Trim(), DateTimeFormat);
                if (fromRegisterDate == null)
                    fromRegisterDate = DateTime.Now.Date.AddMonths(-1);
                if (DateTime.Now.Date - fromRegisterDate.Value > TimeSpan.FromDays(31))
                {
                    ltrMsg.Text = "Giới hạn hủy đăng ký bảo hành là 31 ngày";
                    return;
                }

                DateTime? toRegisterDate = string.IsNullOrWhiteSpace(txtSearchToDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchToDate.Text.Trim(), DateTimeFormat);
                string phone = txtSearchPhone.Text;
                grvData.DataSource = pa_WarrantyDetail.Paging(currentPage, pageSize, ref totalRow, agencyid, model, productcode, phone, fromRegisterDate, toRegisterDate);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRow;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                ltrInfo.Text = "Tổng cộng: " + totalRow;
            }
            catch { }
        }

        private void BindDropDownData()
        {
            try
            {
                List<pa_Agency> list;
                bool isAdmin = IsRootAdmin();
                if (isAdmin)
                    list = pa_Agency.GetAll();
                else
                    list = pa_Agency.GetAll(CurUser.AgencyID.Value);
                pa_Agency.TransformLevel(ref list);
                foreach (var item in list)
                {
                    ddlSearchAgency.Items.Add(new ListItem(item.AgencyName.ShowNameLevel(item.Level), item.AgencyID.ToString()));
                }
                if (isAdmin)
                    ddlSearchAgency.Items.Insert(0, new ListItem(""));
            }
            catch { }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void btnUnregister_Click(object sender, EventArgs e)
        {
            try
            {
                int id = int.Parse(hdfID.Value);
                string msg = txtLydo.Text.Trim();
                bool sendmsg = chkSendMsg.Checked;
                if (string.IsNullOrEmpty(msg))
                {
                    ltr_validate.Text = "(*)";
                    return;
                }
                using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString))
                {
                    conn.Open();
                    pa_WarrantyDetail objDetail = pa_WarrantyDetail.GetByID(id);
                    if (objDetail != null)
                    {
                        using (SqlTransaction trans = conn.BeginTransaction())
                        {
                            int result = SqlHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, "usp_pa_Warranty_UnRegister", new SqlParameter("@WarrantyDetailID", id));
                            if (result > 0)
                            {
                                if (sendmsg)
                                {
                                    if (msg[msg.Length - 1] == '.')
                                        msg = msg.Remove(msg.Length - 1);
                                    string message = pa_MessagePattern.SingletonInstance[eMessagePattern.MAUHUYDANGKY]
                                        .Replace("(Model)", objDetail.ModelCode)
                                        .Replace("(SoMay)", objDetail.ProductCode)
                                        .Replace("(LyDo)", msg.ToVietnameseWithoutAccent());
                                    SmsMtWaiting.Insert(AppSetting.DefaultSenderName, message, objDetail.AgencyID, objDetail.CustomerPhone);
                                }
                            }
                            //Ghi log dữ liệu
                            InsertChangeLog(string.Format("Hủy đăng ký bảo hành {0} {1}", objDetail.ModelCode, objDetail.ProductCode));
                            trans.Commit();
                        }
                        
                    }
                    BindGridData();
                    RegisterStartUpScript("$('#dialog1').dialog('close');");
                }
            }
            catch (Exception ex)
            {
                SysLog.InsertLog(ex);
                ltrResult.Text = "Có lỗi xảy ra khi hủy đăng ký bảo hành!";
            }
        }
    }
}